package br.com.sol.gui;

import br.com.sol.controle.Bluetooth;
import br.com.sol.controle.BluetoothListener;
import br.com.sol.controle.EventosBluetoothReceiver;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.util.Log;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class TelaContatos extends Activity implements BluetoothListener {
	
	private static final String TAG = "BuscaBluetooth";
	private EventosBluetoothReceiver bluetooth; 
    private ArrayAdapter arrayAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.init();
	}
	
	private void init(){
		try {
            bluetooth = Bluetooth.startFindDevices(this, this);
        } catch (Exception e) {
            Log.e(TAG, "Erro: ", e);
        }
		
		setContentView(R.layout.activity_tela_contatos);
		
		arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1);
        ListView listView = (ListView) findViewById(R.id.lv_contatos);
        listView.setAdapter(arrayAdapter);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_tela_contatos, menu);
		return true;
	}

	@Override
	public void action(String action) {
		if (action.compareTo(ACTION_DISCOVERY_STARTED) == 0) {
            arrayAdapter.add("- Busca iniciada");
        } else if (action.compareTo(ACTION_DISCOVERY_FINISHED) == 0) {
            preencherLista();
            arrayAdapter.add("- Fim de busca.");
        }
	}
	
	private void preencherLista() {
        for (BluetoothDevice device : bluetooth.getLista()) {
            arrayAdapter.add(device.getName() + "\n" + device.getAddress());
        }
    }
}
